"""
此文件为对接微信服务号所需工具类
"""
import json
import urllib.request


class ResultCode:
    """
    微信全局返回码
    """
    # 系统繁忙
    SYSTEM_IS_BUSY = -1
    # 成功
    SUCCESS = 0
    # 授权码错误
    ACCESS_TOKEN_ERROR = 40002


# 开发者ID(AppID)
APP_ID = "wx4dc97666826255ba"
# 开发者密码(AppSecret)
APP_SECRET = "bf576106425a7247b4b219233f1e8aee"
# CODE回调地址
CODE_REDIRECT = "http%3a%2f%2ftanqin520.udutech.com%2flogin%2faccredit"


def get_code_address(state):
    """
    获取Code授权地址
    :param state: 回调状态
    :return: Code授权地址
    """
    # 获取Code地址
    code_address = "https://open.weixin.qq.com/connect/oauth2/authorize" \
                   "?appid=" + APP_ID + "" \
                                        "&redirect_uri=" + CODE_REDIRECT + "" \
                                        "&response_type=code" \
                                        "&scope=snsapi_base" \
                                        "&state=" + state + "#wechat_redirect"
    return code_address


def get_user_access_token(code):
    """
    获取通过code换取用户access_token接口地址
    :param code: 用户授权码
    :return: 接口地址
    """
    user_access_token_address = "https://api.weixin.qq.com/sns/oauth2/access_token" \
                                "?appid=" + APP_ID + "" \
                                "&secret=" + APP_SECRET + "" \
                                "&code=" + code + "" \
                                "&grant_type=authorization_code"
    return user_access_token_address


def get_user_info(code):
    """
    通过code获取用户信息
    :param code: 用户信息授权码
    :return: 用户信息字典
    """
    # 接口地址
    url = get_user_access_token(code)
    # 请求接口
    file = urllib.request.urlopen(url)
    # 转换为用户信息
    user_info_dict = json.loads(file.read().decode())
    # 返回信息
    return user_info_dict
